<?php

namespace app\api\controller;


use app\admin\model\Block as BlockModel;
use EasyWeChat\Factory;
use fast\Random;
use think\facade\Log;
use think\facade\Validate;
use think\facade\Config;
use think\facade\Db;
use think\facade\Env;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\controller\Api;
use app\admin\model\User as UserModel;
use  third\Esign;
use think\facade\Event;

/**
 * 会员接口.
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'auth_notify'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();


    }

    public function login()
    {
        global $is_reg ;
        $is_reg = 0;
        try {
            $wxinfo = [];
            if (!Env::get('app.test_uid')) {
                $code = $this->request->get('code');
                $config = config('wechat');

//                dump($config);die;
                $app = Factory::miniProgram($config);
                $rs = $wxinfo = $app->auth->session($code);
                if (isset($rs['errcode'])) {
                    throw  new \Exception($rs['errmsg']);
                }
                $no = rand(10000, 99999);
                $data = [
                    'nickname' => '微信用户' . $no,
                    'username' => '微信用户' . $no,
                    'gender' => 0,
                    'sex' => 0,
                    'status' => 'normal',
//                'unionid' => isset($user['original']['unionid']) ? $user['original']['unionid'] : '',
                    'openid' => $rs['openid'],
                    'session_key' => $rs['session_key'],
                    'avatar' => $this->request->domain() . '/assets/img/avatar.png',
                    'level'=>10002,
                ];
                $rs = $this->auth->miniAppLogin($data['openid'], $data);
                if (!$rs) {
                    $this->error($this->auth->getError());
                }
            } else {
                $this->auth->direct(Env::get('app.test_uid'));
            }
            cache('session_key_'.$this->auth->id,isset($wxinfo['session_key'])?$wxinfo['session_key']:'');
            $userinfo =$this->auth->getUserinfo();
            $UserModel = (new UserModel())->where(['id' => $this->auth->id])->update(['pop'=>0]);
            $this->success(lang('成功'), [
                'userinfo' => $userinfo,
                'wxinfo' => $wxinfo,
                'is_reg'=>$userinfo['pop']
            ]);
        } catch (\Throwable $t) {
            $this->error($t->getMessage());
        }

    }


    /**
     * 获取手机号
     * @return void
     */
    public function getMobile()
    {
        try {
            $encryptedData = $this->request->post('encryptedData');
            $iv = $this->request->post('iv');
            $session_key = cache('session_key_'.$this->auth->id)?:$this->request->post('session_key');
            $config = config('wechat');

            file_put_contents('text.txt',$session_key.PHP_EOL,FILE_APPEND);

            $app = Factory::miniProgram($config);
            $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
            // dump($decryptedData);die;

            if (isset($decryptedData['errcode']) && $decryptedData['errcode'] !== 0) {
                throw  new \Exception($decryptedData['errmsg']);
            }
            $UserModel = new UserModel();
            $UserModel->where(['id' => $this->auth->id])->update(['mobile' => $decryptedData['phoneNumber']]);
            $this->success(lang('成功'), ['phone' => $decryptedData['phoneNumber']]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }


    public function updateInfo()
    {

//        $username = $this->request->get('username');
        $nickname = $this->request->get('nickname');
        $avatar = $this->request->get('avatar');
        $gender = $this->request->get('gender');
//        $birthday = $this->request->get('birthday');
        $area_id = $this->request->get('area_id');
        $birthday = $this->request->get('birthday');
        $mobile = $this->request->get('mobile');
        $email = $this->request->get('email');


        if ($mobile && !isMobile($mobile)) {
            $this->error('手机号格式错误');
        }

        if ($email && !is_email($email)) {
            $this->error('邮箱格式错误');
        }
        $UserModel = new UserModel();
        $user = $UserModel->where(['id' => $this->auth->id])->find();
//        $username && $user->username = $username;
        $avatar && $user->avatar = $avatar;
        $gender && $user->gender = $gender;
        $gender && $user->sex = $gender;
        $birthday && $user->birthday = $birthday;
        $area_id && $user->area_id = $area_id;
        $mobile && $user->mobile = $mobile;
        $email && $user->email = $email;
        $nickname && $user->nickname = $nickname;

        $user->save();
        $this->success(lang('成功'));
    }


    /**
     * 修改手机号.
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }


    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request('type');
        $mobile = $this->request->request('mobile');
        $email = $this->request->request('email');
        $newpassword = $this->request->request('newpassword');
        $captcha = $this->request->request('captcha');
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::where('mobile', $mobile)->find();
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, 'email')) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::where('email', $email)->find();
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户详情
     * @return void
     */
    public function userinfo()
    {

        $UserModel = new UserModel();
        $info = $UserModel
            ->where('id', $this->auth->id)
            ->field('id,nickname,username,avatar,mobile,status,logintime,jointime,viptime,xieyi,level,prevtime,is_auth,idcard,psnId')
            ->find();
        $info['vip_num'] = $info['viptime'] > time() ? ceil(($info['viptime'] - time()) / 86400) : 0;
        $info['is_auth'] = (int)$info['is_auth'];
        //如果身份证没有 查询用户信息
        if (!$info['idcard'] && $info['psnId']) {
            $Esign = new Esign();
            $data = $Esign->personsIdentityInfo($info['psnId']);
            if ($data['code'] == 0) {
                $info['username'] =  $update['username'] = $data['data']['psnInfo']['psnName'];
                $update['idcard'] = $data['data']['psnInfo']['psnIDCardNum'];
                $UserModel->where('id', $this->auth->id)->update($update);
            }
        }

        //这个会员等级存在的话 显示
       $levelinfo =  (new \app\admin\model\Label())->where('id',$info['level'])->find();
        if ($levelinfo && $levelinfo['status']==1){
            $info['level_icon'] =$levelinfo['icon'] ;
            $info['level_func'] = explode(',',$levelinfo['func']);
        }
        $viplevel = [
            'urltype'=>'miniapp',
            'url'=>'/pages/pageDetail?newsId='.$levelinfo['news_id'],
        ];


        $this->success(lang('成功'), [
            'userinfo' => $info,
            'viplevel' => $viplevel,
        ]);
    }

    /**
     * 实名
     */
    public function auth()
    {
        $Esign = new Esign();

        if ($this->auth->is_auth == 1) {
            $this->error('您已完成实名认证，无需重复');
        }
        if (!$this->auth->mobile) {
            $this->error('请先完善手机号');
        }
        $notifyurl = $this->request->domain() . '/api/esign/notify';
        $redirect_url = 'wechat://back';
        $data = $Esign->psnAuthorizehUrl($this->auth->mobile, $redirect_url, $notifyurl);
        if ($data['code'] != 0) {
            $this->error("{$data['code']}:" . $data['message']);
        }
        $UserModel = new UserModel();
        $UserModel->where('id', $this->auth->id)->update(['authFlowId' => $data['data']['authFlowId']]);
        $this->success('成功', $data['data']);
    }

}

